const { create, query, update } = require('../../helper/db');
const { door, ok, now } = require('../../helper/util');
const { getNotifyIO, getNotifyID } = require('../../socket/notify');

/**
 * @apiDefine ErrorResponse
 * @apiError (请求错误) {String} err_message 错误信息描述
 */

/**
 * @apiVersion 1.0.0
 * @apiGroup 好友
 * @api {POST} api/friend/create 申请添加好友
 * @apiName api/friend/create
 * @apiExample {js} axios 例子:
 *  axios.post('http://39.105.38.34:8080/api/friend/create', {
 *    friendUserID: 2,
 *  });
 * @apiParam  {String} friendUserID 想要添加的用户 ID
 * @apiSuccess (请求成功) {Null} data 请求成功后不会返回数据
 * @apiuse  ErrorResponse
 */

module.exports = async ctx => {
  var notify = getNotifyIO();
  var token = ctx.headers.authorization;
  var params = ctx.request.body;
  var user = await door(token);
  var relationlist = await query('select * from relation_ship where userid = ? and friendID = ?', [user.id, params.friendUserID]);

  if (relationlist.length) {
    var relation = relationlist[0];
    var relation = await update('relation_ship', { ...relation, status: 1 });

    if (notify[params.friendUserID]) {
      notify[params.friendUserID].emit('message', {
        kind: 1,
        data: { relation, user },
      });
    }

    ctx.body = ok(null);
    return;
  }

  var relation = await create('relation_ship', {
    userid: user.id,
    friendID: params.friendUserID,
    remark: '',
    status: 1, // 1: 申请中, 2: 成功建立好友关系
    createdat: now(),
  });

  if (notify[params.friendUserID]) {
    notify[params.friendUserID].emit('message', {
      kind: 1,
      data: { relation, user },
    });
  }

  ctx.body = ok(null);
}
